package framework.states;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import org.newdawn.slick.AngelCodeFont;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;

import framework.C;

public class CreateFight extends BackableState {

	int dots = 0;

	int count = 0;

	Thread thread;

	boolean yo = false;
	
	String connectNotification;
	
	StateBasedGame game;
	
	AngelCodeFont font;
	

	@Override
	public void init(GameContainer gc, StateBasedGame game)
			throws SlickException {
		super.init(gc, game);
		connectNotification = "";
		font = new AngelCodeFont(C.FONTS_FOLDER + "little.fnt", C.FONTS_FOLDER + "little.png");
	}



	@Override
	public void render(GameContainer gc, StateBasedGame game, Graphics g)
			throws SlickException {
		String dot;
		switch(dots) {
		case 1 : dot = ".";
		break;
		case 2 : dot = "..";
		break;
		case 3 : dot = "...";
		break;		
		default : dot = "";
		break;
		}
		
		g.setFont(font);

		try {
			URL whatismyip = new URL("http://checkip.amazonaws.com");
			BufferedReader in = new BufferedReader(new InputStreamReader(
					whatismyip.openStream()));
			String ip = in.readLine();
			g.drawString("Address : " + ip, gc.getWidth() / 2 - font.getWidth("Address : " + ip) / 2, gc.getHeight() / 10);
			g.drawString("Waiting for someone to connect" + dot, gc.getWidth() / 2 - font.getWidth("Waiting for someone to connect.") / 2, gc.getHeight() / 4);
		} catch (IOException e) {
			e.printStackTrace();
		}
		g.drawString(connectNotification, 100, 300);
	}

	@Override
	public void update(GameContainer gc, StateBasedGame game, int delta)
			throws SlickException {
		super.update(gc, game, delta);
		count += delta;
		if (count > 250) {
			dots = (dots + 1) % 4;
			count = 0;
		}		

		if (!yo) {
			//thread.run();
			yo = true;
		}
	}

	@Override
	public int getID() {
		return 5;
	}



	@Override
	public void enter(GameContainer container, StateBasedGame game)
			throws SlickException {
		back = false;
		final StateBasedGame oGame = game;
		(new Thread() {
			@Override
			public void run() {
				try {
					ServerSocket serverSocket;
					Socket clientSocket;
					// receiving a response from a remote client
					serverSocket = new ServerSocket(2346);
					clientSocket = serverSocket.accept(); 
					connectNotification = "Fighter connected!";
					Thread.sleep(1000);
					((OnlineFight) oGame.getState(3)).setActivePlayer(1);
					((OnlineFight) oGame.getState(3)).setCommunicationSocket(clientSocket);
					oGame.enterState(3);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
}
